#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import json
import os
import traceback
import web
import time
import datetime
from Umpweb.base import render_jinja
from Umpweb.common import utils
from Umpweb.common.utils import login_required 

from sqlalchemy.orm.exc import NoResultFound
from Umpweb.db import api as db_api
from Umpweb.base import session, _

render = render_jinja('static/templates/oplog', encoding='utf-8',)


class EventList:
    @login_required
    def GET(self):
        permission = 'false'
        if db_api.check_is_adminstrator(session.user.name):
            permission = 'true'
        return render.oplog_list(permission=permission)

class EventExport:
    @login_required

    def GET(self):
        is_update = 'False'
        schedule = None
        interval = None
        sysconfig_for_ump = None

        web.header("Content-Type", "text/plain")
        schedule = db_api.schedule_job_get_with_classname('OplogJob')
        if schedule and schedule.sysconfig_for_ump_id:
            is_update = 'True'
            sysconfig_for_ump = db_api.sysconfig_for_ump_get(schedule.sysconfig_for_ump_id)
            interval = db_api.schedule_interval_get_with_id(schedule.interval_id)
        return render.oplog_export(schedule=schedule, interval=interval, sysconfig_for_ump=sysconfig_for_ump, is_update=is_update)

    def oplog_create(self, x):
        values = {
            'name': x.get('name').strip(),
            'start_date': x.get('start_date').strip(),
            'every': x.get('every').strip(),
            'period': x.get('period').strip(),
            'value_setting':x.get('value_setting').strip(),
            'description':x.get('description').strip(),
            "class_name": 'OplogJob',
            "schedule_type": 'interval',
        }

        body = {"SysconfigForUMPCreate": {'params': values}}
        result = utils.web_return(body)

        result = json.loads(result)

        reply = result['reply']
        records = result['records']

        if reply['is_success'] == 'False':
            raise Exception('create sysconfig_for_ump fail')
        else:
            sys_id = records['id']
            if records and sys_id:
                values['sysconfig_for_ump_id'] = sys_id

            body = {"ScheduleCreate":{'params':values}}
            return utils.web_return(body)

    def oplog_update(self, x):
        values = {
            'name': x.get('name').strip(),
            'start_date': x.get('start_date').strip(),
            'every': x.get('every').strip(),
            'period': x.get('period').strip(),
            'value_setting':x.get('value_setting').strip(),
            'description':x.get('description').strip(),
            "class_name": 'OplogJob',
            "schedule_type": 'interval',
        }

        values['id'] = x.get('schedule_job_id').strip()
        body = {"ScheduleUpdate":{'params':values}}
        result = utils.web_return(body)

        result = json.loads(result)

        reply = result['records']
        sys_id = reply['sysconfig_for_ump_id']
        if sys_id:
            values['id'] = str(sys_id)
            values['value'] = values['value_setting']

        body = {"SysconfigForUMPUpdate": {'params': values}}
        return utils.web_return(body)

    def POST(self):
        web.header("Content-Type", "application/json")
        x = web.input()

        is_update = x.get('is_update')
        if is_update == 'True':
            return self.oplog_update(x)
        else:
            return self.oplog_create(x)


class EventDelete:
    @login_required

    def POST(self):
        x = web.input()
        web.header("Content-Type", "application/json")
        ids = x.get('ids')
        values = {
            'ids': ids,
        }
        body = {"EventDelete": {'params':values}}
        return utils.web_return(body)


class GridEvent:
    def GET(self):
        web_input = web.input()
        search_key = web_input.get('search_key')
        search_val = web_input.get('search_val')
        filters = {}
        if search_key and search_val:
            filters = {'like1':search_val, "search_field":search_key}
        page, total, records, rows = utils.grid_rows_query(db_api.oplog_table, web_input, filters=filters)
        obj_type = ['cluster_id', 'volume_id', 'datacenter', 'host_id']

        for oplog in rows:
            oplog.obj = oplog.oplog_obj
        cells = ['id', 'created_at', 'operation', 'resource', 'obj', 'status', 'detail', 'username']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json
